<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>内容管理后台</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
        }
        
        .navbar-brand {
            font-weight: 700;
        }
        
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            margin-bottom: 2rem;
        }
        
        .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px 15px 0 0 !important;
            padding: 1rem 1.5rem;
        }
        
        .file-item {
            border: 1px solid #e9ecef;
            border-radius: 10px;
            margin-bottom: 1rem;
            transition: all 0.3s ease;
        }
        
        .file-item:hover {
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }
        
        .file-preview {
            width: 100px;
            height: 100px;
            object-fit: cover;
            border-radius: 8px;
        }
        
        .upload-area {
            border: 2px dashed #dee2e6;
            border-radius: 10px;
            padding: 2rem;
            text-align: center;
            background: #f8f9fa;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        
        .upload-area:hover,
        .upload-area.drag-over {
            border-color: #667eea;
            background: #e7f3ff;
        }
        
        .btn-gradient {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            color: white;
        }
        
        .btn-gradient:hover {
            transform: translateY(-1px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
            color: white;
        }
        
        .nav-pills .nav-link.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.25rem rgba(102, 126, 234, 0.15);
        }
        
        .text-editor {
            min-height: 150px;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 10px;
            background: white;
        }
        
        .loading-spinner {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 9999;
            background: rgba(255,255,255,0.9);
            padding: 20px;
            border-radius: 10px;
            display: none;
        }
        
        .file-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 1rem;
        }
        
        .file-card {
            background: white;
            border-radius: 10px;
            padding: 1rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            transition: transform 0.2s ease;
        }
        
        .file-card:hover {
            transform: translateY(-2px);
        }
        
        .text-block {
            background: white;
            border: 1px solid #ddd;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 1rem;
        }
        
        .simple-toolbar {
            margin-bottom: 10px;
            display: flex;
            gap: 5px;
            flex-wrap: wrap;
        }
        
        .toolbar-btn {
            padding: 5px 10px;
            border: 1px solid #ddd;
            background: white;
            border-radius: 3px;
            cursor: pointer;
            font-size: 12px;
        }
        
        .toolbar-btn:hover {
            background: #f0f0f0;
        }
        
        .toolbar-btn.active {
            background: #667eea;
            color: white;
        }
    </style>
</head>
<body>
    <div class="loading-spinner" id="loadingSpinner">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
        </div>
        <p class="mt-2 mb-0">正在加载...</p>
    </div>

    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="#">
                <i class="bi bi-gear-fill me-2"></i>
                内容管理后台
            </a>
            
            <div class="navbar-nav ms-auto">
                <button class="btn btn-outline-light btn-sm" onclick="logout()">
                    <i class="bi bi-box-arrow-right me-1"></i>
                    退出登录
                </button>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-md-3">
                <div class="card">
                    <div class="card-body">
                        <ul class="nav nav-pills flex-column" id="nav-tabs">
                            <li class="nav-item">
                                <a class="nav-link active" href="#content-tab" data-bs-toggle="pill" onclick="switchTab('content')">
                                    <i class="bi bi-card-text me-2"></i>
                                    文字内容
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="#image-tab" data-bs-toggle="pill" onclick="switchTab('image')">
                                    <i class="bi bi-image me-2"></i>
                                    图片管理
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="#video-tab" data-bs-toggle="pill" onclick="switchTab('video')">
                                    <i class="bi bi-camera-video me-2"></i>
                                    视频管理
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="#settings-tab" data-bs-toggle="pill" onclick="switchTab('settings')">
                                    <i class="bi bi-palette me-2"></i>
                                    网站设置
                                </a>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
            
            <div class="col-md-9">
                <div class="tab-content">
                    <!-- 文字内容管理 -->
                    <div class="tab-pane fade show active" id="content-tab">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="mb-0">
                                    <i class="bi bi-card-text me-2"></i>
                                    文字内容管理
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <button type="button" class="btn btn-gradient" onclick="addTextBlock()">
                                        <i class="bi bi-plus-circle me-2"></i>
                                        添加文字块
                                    </button>
                                    <button type="button" class="btn btn-success ms-2" onclick="saveAllContent()">
                                        <i class="bi bi-check-circle me-2"></i>
                                        保存所有内容
                                    </button>
                                </div>
                                <div id="text-blocks"></div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 图片管理 -->
                    <div class="tab-pane fade" id="image-tab">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="mb-0">
                                    <i class="bi bi-image me-2"></i>
                                    图片管理
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="upload-area" onclick="document.getElementById('imageInput').click()">
                                    <input type="file" id="imageInput" multiple accept="image/*" style="display: none;" onchange="uploadFiles(this, 'image')">
                                    <i class="bi bi-cloud-upload display-4 text-muted"></i>
                                    <p class="mt-2 mb-0">点击或拖拽上传图片</p>
                                    <small class="text-muted">支持 JPG, PNG, GIF 格式，最大10MB</small>
                                </div>
                                <div id="image-list" class="file-grid mt-4"></div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 视频管理 -->
                    <div class="tab-pane fade" id="video-tab">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="mb-0">
                                    <i class="bi bi-camera-video me-2"></i>
                                    视频管理
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="upload-area" onclick="document.getElementById('videoInput').click()">
                                    <input type="file" id="videoInput" multiple accept="video/*" style="display: none;" onchange="uploadFiles(this, 'video')">
                                    <i class="bi bi-camera-video display-4 text-muted"></i>
                                    <p class="mt-2 mb-0">点击或拖拽上传视频</p>
                                    <small class="text-muted">支持 MP4, MOV, AVI 格式，最大10MB</small>
                                </div>
                                <div id="video-list" class="file-grid mt-4"></div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 网站设置 -->
                    <div class="tab-pane fade" id="settings-tab">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="mb-0">
                                    <i class="bi bi-palette me-2"></i>
                                    网站设置
                                </h5>
                            </div>
                            <div class="card-body">
                                <form id="settingsForm">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label for="siteTitle" class="form-label">网站标题</label>
                                                <input type="text" class="form-control" id="siteTitle" name="title">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label for="primaryColor" class="form-label">主题色</label>
                                                <input type="color" class="form-control form-control-color" id="primaryColor" name="primaryColor">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="siteDescription" class="form-label">网站描述</label>
                                        <textarea class="form-control" id="siteDescription" name="description" rows="3"></textarea>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="backgroundColor" class="form-label">背景色</label>
                                        <input type="color" class="form-control form-control-color" id="backgroundColor" name="backgroundColor">
                                    </div>
                                    
                                    <button type="submit" class="btn btn-gradient">
                                        <i class="bi bi-check-circle me-2"></i>
                                        保存设置
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let config = {};
        let textBlocks = [];
        let currentTab = 'content';
        let saveTimeout = null;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', async () => {
            showLoading();
            try {
                await loadConfig();
                initializeCurrentTab();
            } catch (error) {
                console.error('初始化失败:', error);
                showAlert('danger', '页面初始化失败');
            } finally {
                hideLoading();
            }
        });

        function showLoading() {
            document.getElementById('loadingSpinner').style.display = 'block';
        }

        function hideLoading() {
            document.getElementById('loadingSpinner').style.display = 'none';
        }

        async function loadConfig() {
            try {
                const response = await fetch('/api/config');
                config = await response.json();
            } catch (error) {
                console.error('加载配置失败:', error);
                throw error;
            }
        }

        function switchTab(tabName) {
            currentTab = tabName;
            setTimeout(initializeCurrentTab, 100);
        }

        function initializeCurrentTab() {
            switch(currentTab) {
                case 'content':
                    renderTextBlocks();
                    break;
                case 'image':
                    renderFileList('image');
                    break;
                case 'video':
                    renderFileList('video');
                    break;
                case 'settings':
                    renderSettings();
                    break;
            }
        }

        function renderTextBlocks() {
            const container = document.getElementById('text-blocks');
            if (!container) return;
            
            container.innerHTML = '';
            textBlocks = [];
            
            const texts = config.content?.texts || [];
            
            if (texts.length === 0) {
                addTextBlock();
            } else {
                texts.forEach((text, index) => {
                    addTextBlock(text.content, index);
                });
            }
        }

        function addTextBlock(content = '', index = -1) {
            const container = document.getElementById('text-blocks');
            if (!container) return;
            
            const blockId = index >= 0 ? index : textBlocks.length;
            
            const blockDiv = document.createElement('div');
            blockDiv.className = 'text-block';
            blockDiv.innerHTML = `
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <h6 class="mb-0">文字块 ${blockId + 1}</h6>
                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeTextBlock(${blockId})">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
                <div class="simple-toolbar">
                    <button type="button" class="toolbar-btn" onclick="formatText(${blockId}, 'bold')">
                        <i class="bi bi-type-bold"></i>
                    </button>
                    <button type="button" class="toolbar-btn" onclick="formatText(${blockId}, 'italic')">
                        <i class="bi bi-type-italic"></i>
                    </button>
                    <button type="button" class="toolbar-btn" onclick="formatText(${blockId}, 'underline')">
                        <i class="bi bi-type-underline"></i>
                    </button>
                </div>
                <textarea class="form-control text-editor" id="editor-${blockId}" placeholder="输入文字内容..." oninput="scheduleAutoSave()">${content || ''}</textarea>
            `;
            
            container.appendChild(blockDiv);
            textBlocks.push({ id: blockId, element: blockDiv });
        }

        function removeTextBlock(blockId) {
            if (!confirm('确定要删除这个文字块吗？')) return;
            
            textBlocks = textBlocks.filter(block => {
                if (block.id === blockId) {
                    block.element.remove();
                    return false;
                }
                return true;
            });
            
            scheduleAutoSave();
        }

        function formatText(blockId, command) {
            const editor = document.getElementById(`editor-${blockId}`);
            if (!editor) return;
            
            editor.focus();
            document.execCommand(command, false, null);
        }

        function renderFileList(type) {
            const container = document.getElementById(`${type}-list`);
            if (!container) return;
            
            const files = config.content?.[type + 's'] || [];
            container.innerHTML = '';
            
            if (files.length === 0) {
                container.innerHTML = `<p class="text-muted text-center py-4">暂无${type === 'image' ? '图片' : '视频'}文件</p>`;
                return;
            }
            
            files.forEach(file => {
                const fileCard = document.createElement('div');
                fileCard.className = 'file-card';
                
                const preview = type === 'image' 
                    ? `<img src="${file.path}" class="file-preview w-100" style="height: 150px;" alt="${file.originalname}">`
                    : `<video src="${file.path}" class="file-preview w-100" style="height: 150px;" muted></video>`;
                
                fileCard.innerHTML = `
                    ${preview}
                    <div class="mt-2">
                        <h6 class="mb-1 text-truncate">${file.originalname}</h6>
                        <small class="text-muted d-block">
                            ${formatFileSize(file.size)}
                        </small>
                        <button class="btn btn-sm btn-outline-danger mt-2 w-100" onclick="deleteFile('${file.id}')">
                            <i class="bi bi-trash me-1"></i>删除
                        </button>
                    </div>
                `;
                
                container.appendChild(fileCard);
            });
        }

        async function uploadFiles(input, type) {
            const files = input.files;
            if (!files.length) return;
            
            showLoading();
            
            for (let file of files) {
                const formData = new FormData();
                formData.append('file', file);
                
                try {
                    const response = await fetch('/admin/upload', {
                        method: 'POST',
                        body: formData
                    });
                    
                    const result = await response.json();
                    
                    if (result.success) {
                        if (!config.content[type + 's']) {
                            config.content[type + 's'] = [];
                        }
                        config.content[type + 's'].push(result.file);
                        showAlert('success', `${file.name} 上传成功`);
                    } else {
                        showAlert('danger', `上传失败: ${result.message}`);
                    }
                } catch (error) {
                    console.error('上传失败:', error);
                    showAlert('danger', `${file.name} 上传失败`);
                }
            }
            
            input.value = '';
            renderFileList(type);
            hideLoading();
        }

        async function deleteFile(fileId) {
            if (!confirm('确定要删除这个文件吗？')) return;
            
            showLoading();
            
            try {
                const response = await fetch(`/admin/file/${fileId}`, {
                    method: 'DELETE'
                });
                
                const result = await response.json();
                
                if (result.success) {
                    ['images', 'videos'].forEach(type => {
                        if (config.content[type]) {
                            config.content[type] = config.content[type].filter(file => file.id !== fileId);
                        }
                    });
                    
                    renderFileList('image');
                    renderFileList('video');
                    showAlert('success', '文件删除成功');
                } else {
                    showAlert('danger', '删除失败: ' + result.message);
                }
            } catch (error) {
                console.error('删除失败:', error);
                showAlert('danger', '删除失败');
            } finally {
                hideLoading();
            }
        }

        function renderSettings() {
            document.getElementById('siteTitle').value = config.title || '';
            document.getElementById('siteDescription').value = config.description || '';
            document.getElementById('primaryColor').value = config.theme?.primaryColor || '#007bff';
            document.getElementById('backgroundColor').value = config.theme?.backgroundColor || '#ffffff';
        }

        function scheduleAutoSave() {
            if (saveTimeout) {
                clearTimeout(saveTimeout);
            }
            saveTimeout = setTimeout(saveAllContent, 2000); // 2秒后自动保存
        }

        async function saveAllContent() {
            const texts = [];
            textBlocks.forEach(block => {
                const editor = document.getElementById(`editor-${block.id}`);
                if (editor && editor.value.trim()) {
                    texts.push({ content: editor.value });
                }
            });
            
            try {
                const response = await fetch('/admin/config', {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({texts: texts})
                });
                
                const result = await response.json();
                if (result.success) {
                    config.content.texts = texts;
                    showAlert('success', '内容保存成功', 1000);
                } else {
                    showAlert('danger', '保存失败: ' + result.message);
                }
            } catch (error) {
                console.error('保存失败:', error);
                showAlert('danger', '保存失败');
            }
        }

        document.getElementById('settingsForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            showLoading();
            
            const formData = new FormData(e.target);
            const settings = {
                title: formData.get('title'),
                description: formData.get('description'),
                theme: {
                    primaryColor: formData.get('primaryColor'),
                    backgroundColor: formData.get('backgroundColor')
                }
            };
            
            try {
                const response = await fetch('/admin/config', {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(settings)
                });
                
                const result = await response.json();
                
                if (result.success) {
                    Object.assign(config, settings);
                    showAlert('success', '设置保存成功');
                } else {
                    showAlert('danger', '保存失败: ' + result.message);
                }
            } catch (error) {
                console.error('保存失败:', error);
                showAlert('danger', '保存失败');
            } finally {
                hideLoading();
            }
        });

        async function logout() {
            try {
                await fetch('/admin/logout', {method: 'POST'});
                window.location.href = '/admin/login';
            } catch (error) {
                window.location.href = '/admin/login';
            }
        }

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        function showAlert(type, message, timeout = 3000) {
            const toast = document.createElement('div');
            toast.className = `alert alert-${type} position-fixed top-0 end-0 m-3`;
            toast.style.zIndex = '9999';
            toast.innerHTML = message;
            
            document.body.appendChild(toast);
            
            setTimeout(() => {
                toast.remove();
            }, timeout);
        }

        // 拖拽上传支持
        document.addEventListener('dragover', (e) => {
            e.preventDefault();
        });

        document.addEventListener('drop', (e) => {
            e.preventDefault();
            const uploadArea = e.target.closest('.upload-area');
            if (uploadArea) {
                const input = uploadArea.querySelector('input[type="file"]');
                if (input && e.dataTransfer.files.length) {
                    input.files = e.dataTransfer.files;
                    input.dispatchEvent(new Event('change'));
                }
            }
        });
    </script>
</body>
</html>